/**
 * 
 */
package de.wesemann.mediahandbook.le.activity;

import java.io.FileNotFoundException;
import java.util.concurrent.ExecutionException;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import de.wesemann.jdedun.entities.district.districts.DistrictDistrict;
import de.wesemann.jdedun.entities.district.districts.DistrictDistrictsContainer;
import de.wesemann.mediahandbook.le.R;
import de.wesemann.mediahandbook.le.activity.helper.AbstractAsyncTask;
import de.wesemann.mediahandbook.le.activity.helper.AbstractListActivity;
import de.wesemann.mediahandbook.le.activity.helper.ActivityHelper;
import de.wesemann.mediahandbook.le.adapter.DistrictAdapter;
import de.wesemann.mediahandbook.le.listener.DistrictOverviewEndlessScrollListener;
import de.wesemann.mediahandbook.le.util.DistrictUtil;
import de.wesemann.mediahandbook.le.widget.TitleWidget;

/**
 * @author Lars W.
 * 
 */
public class DistrictOverview extends AbstractListActivity {

	private static String LOG_TAG = DistrictOverview.class.getSimpleName();
	public static String DISTRICT_TAG = "District";
	private TitleWidget titleWidget;
	private LoadItemsTaks mLoadItemsTask;
	private String mSearchValue;
	private DistrictDistrictsContainer mDistrictsContainer;
	private DistrictAdapter mDistrictAdapt;
	private ListView mList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(LOG_TAG, "onCreate()");
		setContentView(R.layout.district_overview);
		setUpTitleWidget();
		mList = (ListView) findViewById(android.R.id.list);
		Object retained = getLastNonConfigurationInstance();
		if (retained instanceof LoadItemsTaks) {
			Log.d(LOG_TAG, "Reclaiming previous background task LoadItems.");
			mLoadItemsTask = (LoadItemsTaks) retained;
			mLoadItemsTask.setActivity(this);
		} else {
			mLoadItemsTask = new LoadItemsTaks(this);
			mLoadItemsTask.execute();
		}

	}

	private void setUpTitleWidget() {
		titleWidget = (TitleWidget) findViewById(R.id.co_titleWidget);
		titleWidget.setTitle(getString(R.string.districts));
		titleWidget.setLeftIcon(R.drawable.bu_house_conf);

		titleWidget.hideProgressBar();
	}

	private void createList() {
		mDistrictAdapt = new DistrictAdapter(this, mDistrictsContainer.getData());
		if (null != mDistrictsContainer.getPaging()) {
			mList.setOnScrollListener(new DistrictOverviewEndlessScrollListener(3, mDistrictAdapt, mList,
					mDistrictsContainer, titleWidget.getProgressBar()));
		}
		setListAdapter(mDistrictAdapt);
	}

	public void onSearchClick(View view) {
		if (view.getId() == R.id.title_search) {
			// Toast.makeText(this, "search clicked",
			// Toast.LENGTH_SHORT).show();
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(getString(R.string.search_title));
			final EditText edit = new EditText(this);
			builder.setView(edit);

			builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					Editable value = edit.getText();
					if (value.toString().length() != 0) {
						mSearchValue = value.toString().trim();
						mSearchValue = mSearchValue.replace(" ", "%20");
						Log.d(LOG_TAG, "I'm looking for " + mSearchValue);
						mLoadItemsTask = new LoadItemsTaks(DistrictOverview.this);
						mLoadItemsTask.execute(mSearchValue);
					}
				}
			});

			builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					// Canceled.
				}
			});

			builder.show();

		}
	}

	private class LoadItemsTaks extends AbstractAsyncTask<String, Void, DistrictDistrictsContainer> {

		protected LoadItemsTaks(ActivityHelper activity) {
			super(activity);
		}

		@Override
		protected DistrictDistrictsContainer doInBackground(String... params) {
			if (params != null && params.length > 0 && params[0] != null && !params[0].isEmpty()) {
				DistrictDistrictsContainer distCont = new DistrictDistrictsContainer();
				try {
					distCont.setData(DistrictUtil.searchDistrictsByName(params[0]));
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return distCont;
			} else {
				try {
					return DistrictUtil.getFirstDistricts(30);
				} catch (FileNotFoundException e) {
					Log.e(LOG_TAG, "Couln't found districts. Maybe Internet problems");
					Log.e(LOG_TAG, e.getMessage());
				}
			}
			return null;
		}

		@Override
		protected void onPreExecute() {
			Log.d(LOG_TAG, "PRE Executing");
			activity.showDialog(LOADING_DIALOG);

		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * de.wesemann.mediahandbook.le.activity.helper.ActivityHelper#reload(de
	 * .wesemann.mediahandbook.le.activity.helper.AbstractAsyncTask)
	 */
	@Override
	public void reload(AbstractAsyncTask<?, ?, ?> task) {

		dismissDialog(LOADING_DIALOG);
		Toast.makeText(this, getString(R.string.error_while_loading), Toast.LENGTH_LONG).show();
		if (task.getreLoadTries() < 3) {
			if (task instanceof LoadItemsTaks) {
				mLoadItemsTask.execute(mSearchValue);
			}
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * de.wesemann.mediahandbook.le.activity.helper.ActivityHelper#onTaskCompleted
	 * (de.wesemann.mediahandbook.le.activity.helper.AbstractAsyncTask)
	 */
	@Override
	public void onTaskCompleted(AbstractAsyncTask<?, ?, ?> task) {
		try {
			mDistrictsContainer = mLoadItemsTask.get();
			if (mDistrictsContainer != null) {
				Log.d(LOG_TAG, "size " + mDistrictsContainer.getData().size());
				createList();
				Toast.makeText(this, getString(R.string.finished), Toast.LENGTH_LONG);
			} else {
				Toast.makeText(this, getString(R.string.error_while_loading), Toast.LENGTH_LONG);
			}

		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}

		if (mShownDialog) {
			dismissDialog(LOADING_DIALOG);
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.ListActivity#onListItemClick(android.widget.ListView,
	 * android.view.View, int, long)
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		DistrictDistrict branch = (DistrictDistrict) getListView().getItemAtPosition(position);
		Intent intent = new Intent(this, CompaniesOverview.class);
		intent.putExtra(DISTRICT_TAG, branch);
		startActivity(intent);
	}

	/**
	 * After a screen orientation change, this method is invoked. As we're going
	 * to state save the task, we can no longer associate it with the Activity
	 * that is going to be destroyed here.
	 */
	@Override
	public Object onRetainNonConfigurationInstance() {
		if (mLoadItemsTask != null) {
			Log.d(LOG_TAG, "Save the LoadItemsTask");
			mLoadItemsTask.setActivity(null);
			return mLoadItemsTask;
		}
		return null;

	}

}
